#include "dev59.h"

#include <httpclient.h>

Dev59::Dev59()
{

}

QString Dev59::name()
{
    return "Dev59";
}

QString Dev59::prefix()
{
    return "https://dev59.com/";
}

QList<QListWidgetItem *> Dev59::searching_item(const QString &text)
{

    QString search_text = text;
    if (search_text.isEmpty()) {
        search_text= name();
    }

    QList<QListWidgetItem *> list;
    QString makedata = QString("{\"requestState\":{\"current\":1,\"filters\":[],\"resultsPerPage\":50,\"searchTerm\":\"%1\",\"sortDirection\":\"\",\"sortField\":\"\",\"sortList\":[]},\"queryConfig\":{\"search_fields\":{\"Title\":{\"weight\":3},\"TitleEn\":{\"weight\":2},\"QuestionBody\":{},\"Tags\":{\"weight\":2}},\"result_fields\":{\"Title\":{},\"QuestionBody\":{},\"Tags\":{},\"Score\":{},\"AnswerCount\":{},\"Id\":{}},\"facets\":{\"Tags.keyword\":{\"type\":\"value\",\"size\":20}}}}").arg(search_text);

    Request req("https://dev59.com/api/search");
    req.setData(Response(0, makedata.toUtf8()).toMap());

    Response resp = HttpClient::instance().post(req);
    auto results = resp.toMap().value("results").toList();
    foreach (auto result, results) {
        auto var = result.toMap();
        auto id_raw = var.value("id").toMap().value("raw").toString();
        auto Title_raw = var.value("Title").toMap().value("raw").toString();

        auto item = newItem();
        item->setText(Title_raw);
        item->setData(990, id_raw);

        list << item;
    }

    return list;
}

QString Dev59::content_item(const QListWidgetItem *item)
{
    auto id_raw = item->data(990).toString();
    return prefix() + id_raw;
}
